package com.mywork.mvpkodeinxml.rx

import android.os.Environment
import android.util.Log
import com.mywork.mvpkodeinxml.common.FILE_DOWNLOAD_PATH
import com.mywork.mvpkodeinxml.model.DownloadListener
import com.mywork.common.utils.FileUtils
import com.zchu.rxcache.data.ResultFrom
import io.reactivex.subscribers.DisposableSubscriber
import okhttp3.ResponseBody
import java.io.*

abstract class DownLoadSubscriber(val fileName: String) : DisposableSubscriber<ResponseBody>(),
    DownloadListener {
    private val ENV_PATH = Environment.getExternalStorageDirectory().toString() + FILE_DOWNLOAD_PATH
    private var filePath: String = ""

    override fun onComplete() {

    }

    override fun onNext(t: ResponseBody) {
        if (!FileUtils.createOrExistsDir(ENV_PATH)) {
            onFailure(Throwable("创建存储文件夹错误!或没有写入存储器权限!"))
        }
        filePath = ENV_PATH + fileName
        val file = File(filePath)
        if (FileUtils.createFileByDeleteOldFile(file)) {
            //下载文件放在子线程
            val thread = object : Thread() {
                override fun run() {
                    super.run()
                    //保存到本地
                    writeFile2Disk(t, file)
                }
            }
            thread.start()
        } else {
            onFailure(Throwable("创建存储文件错误!或没有写入存储器权限!"))
        }

    }

    override fun onError(t: Throwable?) {
        onFailure(t)
    }

    //将下载的文件写入本地存储
    private fun writeFile2Disk(response: ResponseBody, file: File) {
        //downloadListener.onStart();
        var currentLength: Long = 0
        var os: OutputStream? = null

        val byteStream = response.byteStream() //获取下载输入流
        val totalLength = response.contentLength()

        try {
            os = FileOutputStream(file) //输出流
            var len: Int
            val buff = ByteArray(1024)
            len = byteStream.read(buff)
            while (len != -1) {
                os.write(buff, 0, len)
                currentLength += len.toLong()
                Log.e("FileDownLoad", "当前进度: $currentLength")
                //计算当前下载百分比，并经由回调传出
                onProgress(currentLength, totalLength)
                //当百分比为100时下载结束，调用结束回调，并传出下载后的本地路径
                if ((100 * currentLength / totalLength).toInt() == 100) {
                    onFinish(filePath, response.contentType()!!.subtype, totalLength, ResultFrom.Remote) //下载完成
                }
                len = byteStream.read(buff)
            }
        } catch (e: FileNotFoundException) {
            onFailure(e)
        } catch (e: IOException) {
            onFailure(e)
        } finally {
            if (os != null) {
                try {
                    os.close() //关闭输出流
                } catch (e: IOException) {
                    onFailure(e)
                }

            }
            if (byteStream != null) {
                try {
                    byteStream.close() //关闭输入流
                } catch (e: IOException) {
                    onFailure(e)
                }

            }
        }
    }
}